import router from '@/router'
import { useUser } from '@/store/user'
import { useTabs } from '@/store/tabs'

// 路由守卫
router.beforeEach((to, _from, next) => {
  if (!to.meta?.title) {
    //路由异常，跳转首页
    next(localStorage.getItem('firstPath') || '/')
    return
  }
  // 设置页面标题
  const { params } = useUser()
  let title = to.meta?.title
  if (to.query?.title) {
    title = decodeURIComponent(to.query.title as string)
  }
  document.title = `${title} - ${params.AdminName || 'Admin'}`

  // 白名单路由
  const whiteList = ['/login', '/register', '/404', '/403', '/500']

  // 如果访问的是白名单路由，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }

  // 其他情况正常放行
  next()
})

router.afterEach((to) => {
  // 添加标签页
  const { addTab } = useTabs()
  if (to.meta?.title) {
    addTab(to)
  }
})

export default router
